package com.blackfish.common.untils;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class ShaUntil {
	private static volatile ShaUntil shaUntils;
	/**
	　　* 将byte转为16进制
	　　* @param bytes
	　　* @return
	　　*/
	public ShaUntil(){}

	public static ShaUntil getInstance(){
		synchronized (ShaUntil.class) {
			if (shaUntils == null) {
				shaUntils = new ShaUntil();
			}
		}
		return shaUntils;
	}

	private static String byte2Hex(byte[] bytes){
		StringBuffer stringBuffer = new StringBuffer();
		String temp = null;
		for (int i=0;i<bytes.length;i++){
			temp = Integer.toHexString(bytes[i] & 0xFF);
			if (temp.length()==1){
				//1得到一位的进行补0操作
				stringBuffer.append("0");
			}
				stringBuffer.append(temp);
		}
		return stringBuffer.toString();
	}
	
	public static String getSHA256StrJava(String str){
		MessageDigest messageDigest;
		String encodeStr = "";
		try {
				messageDigest = MessageDigest.getInstance("SHA-256");
				messageDigest.update(str.getBytes("UTF-8"));
				encodeStr = byte2Hex(messageDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encodeStr;
	}

	private String MD5(String s) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] bytes = md.digest(s.getBytes("utf-8"));
			return toHex(bytes);
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static String toHex(byte[] bytes) {

		final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
		StringBuilder ret = new StringBuilder(bytes.length * 2);
		for(int i=0; i<bytes.length; i++) {
			ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
			ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
		}
		return ret.toString();
	}

	public String getPathName(String fileName,String userName){
		return this.MD5(fileName+userName);
	}


}
